﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
namespace RATSharp.Rest
{
    static class RestResponseTaskFactory
    {
        public static Task<T> ExecuteTaskAsync<T>(this RestClient @this, RestRequest request, RestService service)
    where T : new()
        {
            if (@this == null || service == null || request == null)
                throw new NullReferenceException();
            var tcs = new TaskCompletionSource<T>();
            if (service.sessionCookie != null)
            {
                request.AddCookie(service.sessionCookie.Name, service.sessionCookie.Value);
            }

            IRestResponse<T> response = @this.Execute<T>(request);

            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                try
                {
                    @this.Authenticator = new HttpBasicAuthenticator(service.properties.username, service.properties.password);
                    //Try to send data again with manager
                    response = @this.Execute<T>(request);
                }
                finally
                {
                    @this.Authenticator = null;
                }
            }


            foreach (RestResponseCookie cookie in response.Cookies)
            {
                if (cookie.Name.Equals(RestService.SESSION_COOKIE_KEY))
                {
                    service.sessionCookie = cookie;
                }
            }

            if (response.ErrorException != null)
            {
                tcs.TrySetException(response.ErrorException);
            }
            else
            {
               //Console.WriteLine(response.Content);
                tcs.TrySetResult(response.Data);
            }
            return tcs.Task;
        }


    }
}
